<?php

namespace IDock\Insurance\TPBX;

use IDock\IDock\IDockInterface;
use IDock\Insurance\TPBX\Request\CancelOrderNoRequest;
use IDock\Insurance\TPBX\Request\CarModelQueryRequest;
use IDock\Insurance\TPBX\Request\EPolicyDownloadRequest;
use IDock\Insurance\TPBX\Request\GetCarVerifyCodeRequest;
use IDock\Insurance\TPBX\Request\GetOrderNoRequest;
use IDock\Insurance\TPBX\Request\GetPaymentUrlRequest;
use IDock\Insurance\TPBX\Request\GetVerifyCodeRequest;
use IDock\Insurance\TPBX\Request\InsuranceConfirmRequest;
use IDock\Insurance\TPBX\Request\NonCarProductDetailRequest;
use IDock\Insurance\TPBX\Request\NonCarProductListRequest;
use IDock\Insurance\TPBX\Request\OfferOrderPriceRequest;
use IDock\Insurance\TPBX\Request\OrderCancelRequest;
use IDock\Insurance\TPBX\Request\OrderPriceQueryRequest;
use IDock\Insurance\TPBX\Request\OrderStatusQueryRequest;
use IDock\Insurance\TPBX\Request\PolicyPaymentRequest;
use IDock\Insurance\TPBX\Request\PremiumInquiryRequest;
use IDock\Insurance\TPBX\Request\ProposalStatusRequest;
use IDock\Insurance\TPBX\Request\RenewalInquiryRequest;
use IDock\Insurance\TPBX\Request\RevokeOrderNoRequest;
use IDock\Insurance\TPBX\Request\UnderwritingRequest;
use IDock\Insurance\TPBX\Request\UploadFileRequest;
use IDock\Insurance\TPBX\Request\VehicleConfirmRequest;
use IDock\Insurance\TPBX\Request\VehicleModelRequest;
use IDock\Insurance\TPBX\Response\CancelOrderResponse;
use IDock\Insurance\TPBX\Response\EPolicyDownloadResponse;
use IDock\Insurance\TPBX\Response\InsuranceConfirmResponse;
use IDock\Insurance\TPBX\Response\InsurancePriceQueryResponse;
use IDock\Insurance\TPBX\Response\NonCarProductDetailResponse;
use IDock\Insurance\TPBX\Response\NonCarProductListResponse;
use IDock\Insurance\TPBX\Response\OrderStatusQueryResponse;
use IDock\Insurance\TPBX\Response\PolicyPaymentResponse;
use IDock\Insurance\TPBX\Response\PremiumInquiryResponse;
use IDock\Insurance\TPBX\Response\ProposalStatusResponse;
use IDock\Insurance\TPBX\Response\RenewalInquiryResponse;
use IDock\Insurance\TPBX\Response\UnderwritingResponse;
use IDock\Insurance\TPBX\Response\UploadFileResponse;
use IDock\Insurance\TPBX\Response\VehicleActualValueResponse;
use IDock\Insurance\TPBX\Response\VehicleConfirmResponse;
use IDock\Insurance\TPBX\Response\VehicleModelResponse;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\NonCar\NonCarUnderwritingPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\PremiumUnderwritingPrinter;
use IDock\Printer\SpecialClausesPrinter;
use IDock\Printer\VehicleActualValuePrinter;
use IDock\Visitor\EPolicyDownloadVisitor;
use IDock\Visitor\NonCar\NonCarInquiryVisitor;
use IDock\Visitor\NonCar\NonCarProductListVisitor;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\PolicyInfoVisitor;
use IDock\Visitor\PolicyPaymentVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\ProposalRecallVisitor;
use IDock\Visitor\ProposalStatusVisitor;
use IDock\Visitor\RenewalInquiryVisitor;
use IDock\Visitor\UnderwritingRecallVisitor;
use IDock\Visitor\UploadFileVisitor;
use IDock\Visitor\VehicleActualValueVisitor;
use IDock\Visitor\VehicleModelVisitor;

/**
 * 珠峰保险
 */
class TPBXConstruct extends Builder implements IDockInterface
{

    protected $config = [];

    public function __construct($config)
    {
        $this->config = $config;
        $this->channelName = $config['channelName'] ?? '';
        $this->appId = $config['appId'] ?? '';
        $this->appKey = $config['appKey'] ?? '';
        $this->notifyUrl = $config['notifyUrl'] ?? '';
        $this->fileGateway = $config['fileGateway'] ?? '';
    }

    /**
     * 车型查询
     * @param VehicleModelVisitor $vehicleModelVisitor
     * @return VehicleModelResponse
     */
    public function vehicleModel(VehicleModelVisitor $vehicleModelVisitor): VehicleModelResponse
    {
        $request = new VehicleModelRequest();
        $request->setVisitor($vehicleModelVisitor);

        /*** @var VehicleModelResponse $response */
        $response = $this->execute($request);
        return $response;
    }

    /**
     * 续保查询
     * @param RenewalInquiryVisitor $renewalInquiryVisitor
     * @return RenewalInquiryResponse
     * @version 4.0
     */
    public function renewalInquiry(RenewalInquiryVisitor $renewalInquiryVisitor): RenewalInquiryResponse
    {
        $request = new RenewalInquiryRequest();
        $request->setVisitor($renewalInquiryVisitor);
//        global $testResponse;
        /*        $testResponse = '<?xml version="1.0" encoding="utf-8"?><Packet><Head><returnCode>0000</returnCode><returnMsg>业务处理成功</returnMsg><requestType>N0201</requestType><sign>50414f76ab659ea9794b64c4673b6a14</sign><timeStamp>20240628163827</timeStamp></Head><Body><renewBase><orderNo>HXY0ff6a81719563907480</orderNo><amOrderNo></amOrderNo><oldBusiFlag>1</oldBusiFlag></renewBase><oldBusiPolicy><oldBusiPolicyNO>2052895100002023000012</oldBusiPolicyNO><prodNo>0528</prodNo><Isinstantflag>0</Isinstantflag><oldBusiStartDate>20230705000000</oldBusiStartDate><oldBusiEndDate>20240705000000</oldBusiEndDate></oldBusiPolicy><oldCIPolicy><oldCIPolicyNO>2059095100002023000123</oldCIPolicyNO><prodNo>0590</prodNo><Isinstantflag>0</Isinstantflag><oldCIStartDate>20230705000000</oldCIStartDate><oldCIEndDate>20240705000000</oldCIEndDate></oldCIPolicy><vehicle><vehicleId>BYAAYD0002</vehicleId><vehicleName>比亚迪BYD7005BEV纯电动轿车</vehicleName><vehiclePlatId></vehiclePlatId><vehiclePrice>219800.0</vehiclePrice><vehicleActualPrice>211887.2</vehicleActualPrice><noLicenseFlag>0</noLicenseFlag><licensePlateNo>川SSS911</licensePlateNo><licensePlateType>01</licensePlateType><motorTypeCode>11</motorTypeCode><vehicleStyle>K11</vehicleStyle><firstRegisterDate>2022-12-13</firstRegisterDate><vin>LFDE1MN5445411111</vin><engineNo>57054121111111</engineNo><seatCount>5</seatCount><limitLoad>0.0</limitLoad><wholeWeight>1850.0</wholeWeight><displaceMent>0.001</displaceMent><Power>0.0</Power><fuelType>C</fuelType><useNature>85</useNature><drivePermitDate>2019-12-21 00:00:00.0</drivePermitDate></vehicle><applicant><appName>李阳与</appName><appType>1</appType><appNature>1</appNature><certfCls>01</certfCls><certfCode>513823199706131515</certfCode><certfValidStartDate>2008-12-21</certfValidStartDate><certfValidEndDate>2999-12-31</certfValidEndDate><appBirthday>19970613</appBirthday><appMobile>18228376531</appMobile><postCode></postCode><appAddress>四川省成都市大邑县小南街</appAddress><appSex>1</appSex><appNationality></appNationality><appEmail>2471645450@163.com</appEmail><appNation></appNation><appIssuer></appIssuer><appCompanyType></appCompanyType><appAddressCode>510000-510100-510129</appAddressCode></applicant><appInsured><insuredName>李阳与</insuredName><insuredType>1</insuredType><insuredNature>1</insuredNature><certfCls>01</certfCls><certfCode>513823199706131515</certfCode><certfValidStartDate>2008-12-21</certfValidStartDate><certfValidEndDate>2999-12-31</certfValidEndDate><insuredBirthday>19970613</insuredBirthday><insuredMobile>18228376531</insuredMobile><postCode></postCode><insuredAddress>四川省成都市大邑县小南街</insuredAddress><insuredSex>1</insuredSex><insuredNationality></insuredNationality><insuredEmail>2471645450@163.com</insuredEmail><insureNation></insureNation><insureIssuer></insureIssuer><insureCompanyType></insureCompanyType><insureAddressCode>510000-510100-510129</insureAddressCode></appInsured><vehicleOwner><vehicleOwnerName>李阳与</vehicleOwnerName><vehicleOwnerIdentifyType>01</vehicleOwnerIdentifyType><vehicleOwnerIdentifyNumber>513823199706131515</vehicleOwnerIdentifyNumber><certfValidStartDate>2008-12-21</certfValidStartDate><certfValidEndDate>2999-12-31</certfValidEndDate><vehicleOwnerBirth>19970613</vehicleOwnerBirth><vehicleOwnerSex>1</vehicleOwnerSex><vehicleOwnerType>1</vehicleOwnerType><vehicleOwnerMobile>18228376531</vehicleOwnerMobile><vehicleOwnerAddress>四川省成都市大邑县小南街</vehicleOwnerAddress><vehicleAddressCode>510000-510100-510129</vehicleAddressCode><postCode></postCode><vehicleNation></vehicleNation><vehicleIssuer></vehicleIssuer><vehicleOwnerEmail>2471645450@163.com</vehicleOwnerEmail></vehicleOwner><renewItemKind><coverageItem><coverageCode>0401200</coverageCode><sumLimit>211887.20</sumLimit><noDduct></noDduct><glsType></glsType><repairFactoryType></repairFactoryType><rate></rate><unit>0</unit><unitAmount>0.00</unitAmount><unclaimAmount></unclaimAmount><deductibleRate></deductibleRate><serverTime></serverTime><sharedSumInsurd></sharedSumInsurd></coverageItem></renewItemKind></Body></Packet>';*/
        /*** @var RenewalInquiryResponse $response */
        $response = $this->execute($request);
        return $response;
    }

    /**
     * 车辆实际价格接口
     * @param VehicleActualValueVisitor $vehicleActualValueVisitor
     * @return
     */
    public function vehicleActualValue(VehicleActualValueVisitor $vehicleActualValueVisitor)
    {
        $response = new VehicleActualValueResponse();
        $response->setCode('200');
        $vehicleActualValuePrinter = new VehicleActualValuePrinter();
        $response->printer = $vehicleActualValuePrinter;
        return $response;
    }

    /**
     * 询价前置
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return
     */
    public function preInquiry(PremiumInquiryVisitor $premiumInquiryVisitor)
    {

    }

    public function validateCar(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
        // TODO: Implement validateCar() method.
    }

    /**
     * 询价
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return
     * @throws \Exception
     */
    public function premiumInquiry(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
        $request = new PremiumInquiryRequest();
        $request->setVisitor($premiumInquiryVisitor);

//global $testResponse;
//        $testResponse = '{"msg":"业务执行异常:[车险核心]报价错误：交强险重复投保，警告：号牌号码“川A1Q5Z0”的保单发生重复投保，与其重复投保的其它公司的保单信息如下：投保确认码 02PAIC510023080271045167009934;保单号 12611893902129927930;起保日期 2023-08-18 00:00;终保日期 2024-08-18 00:00;号牌号码 川A35FV1;号牌种类 02;车架号 LVYPDALA7JP018090;发动机号 7035037;地区 四川。","code":"1000028"}';

        /**@var PremiumInquiryResponse $response * */
        $response = $this->execute($request);
        if ($response->printer->repeatInsuredFlg && boolval($premiumInquiryVisitor->biStartData)) {
            $response->printer->repeatInsurePrinter['biStartData'] = $response->printer->repeatInsurePrinter['ciStartData'];
        }
        if ($response->isSuccess()) {
            $response->buildCoverage($premiumInquiryVisitor->getVehicleVisitor()->isNewEnergy, $premiumInquiryVisitor->getCoverageVisitorList());
        }
        $nonCarInquiryPrinter = new NonCarInquiryPrinter();
        $totalPremium = 0;
        foreach ($premiumInquiryVisitor->getNonCarInquiryVisitor()->getNonCarList() as $item) {
            /*** @var $item NonCarProductVisitor */
            $single = new NonCarInquirySinglePrinter();
            $single->premium = $item->premium;
            $single->planCode = $item->planCode;
            $single->productCode = $item->productCode;
            $single->statusCode = 'success';
            $totalPremium += $single->premium * $item->insuredNum;
            $nonCarInquiryPrinter->noCarInquirySingleAppend($single);
        }
        $nonCarInquiryPrinter->totalPremium = $totalPremium;
        $response->printer->nonCarInquiryPrinter = $nonCarInquiryPrinter;
//        $testResponse = '';
        return $response;
    }

    /**
     * 核保
     * @param PremiumInquiryVisitor $premiumInquiryVisitor
     * @return
     */
    public function underwriting(PremiumInquiryVisitor $premiumInquiryVisitor)
    {
        $attachmentList = [];
        if (!empty($premiumInquiryVisitor->getFileList())) {
            foreach ($premiumInquiryVisitor->getFileList() as $value) {
                $request1 = new UploadFileRequest();
                $uploadFileVisitor = new UploadFileVisitor();
                $uploadFileVisitor->argc = $premiumInquiryVisitor->getExtInfoVisitor()->argc;
                $uploadFileVisitor->fileAppend($value['type'], $value['url'], '');
                $request1->setVisitor($uploadFileVisitor);
                $response1 = $this->execute($request1);
                if ($response1->isSuccess()) {
                    $value['number'] = $response1->number;
                    $attachmentList[] = $value;
                }
            }
        }
        $request = new UnderwritingRequest();
        $request->attachmentList = $attachmentList;
        $request->setVisitor($premiumInquiryVisitor);
//        global $testResponse;
//        $testResponse = '{    "code": "0000",    "msg": "成功",    "data": {        "head": {            "requestType": "V050",            "account": "15520756896_guangdong",            "password": "666666"        },        "basePart": {            "tpTPFApplyNo": "1000105000016043085",            "tpBizApplyNo": "1000109000016043086",            "accidentApplyNo": "",    "healthApplyNo": "",            "attachRulesString": ""        }    }}';
        /**@var UnderwritingResponse $response * */
        $response = $this->execute($request);
        if(!empty($response->printer->argc['nonCarInquiryNo'])){
            /***
             * @var NonCarInquirySinglePrinter $nonCarSingle
             */
            $nonCarSingle = $premiumInquiryVisitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
            if($nonCarSingle){
                $single = new NonCarInquirySinglePrinter();
                $single->planCode = $nonCarSingle->planCode;
                $single->productCode = $nonCarSingle->productCode;
                $single->inquiryNo = $response->printer->argc['nonCarInquiryNo'] ?? '';
                $nonCarInquiryPrinter = new NonCarUnderwritingPrinter();
                $nonCarInquiryPrinter->nonCarSingleAppend($single);
                $response->printer->noCarUnderwritingPrinter = $nonCarInquiryPrinter;
            }
        }
        return $response;
    }

    /**
     * 获取支付链接
     * @param PolicyPaymentVisitor $paymentVisitor
     * @return
     */
    public function policyPayment(PolicyPaymentVisitor $paymentVisitor)
    {
        $request = new PolicyPaymentRequest();
        $request->setVisitor($paymentVisitor);

        /**@var PolicyPaymentResponse $response * */
        $response = $this->execute($request);

        return $response;
    }

    public function proposalStatus(ProposalStatusVisitor $proposalStatusVisitor)
    {
        $request = new ProposalStatusRequest();
        $request->setVisitor($proposalStatusVisitor);

        /**
         * @var ProposalStatusResponse $response
         */
        $response = $this->execute($request);
        return $response;
    }

    public function proposalRecall(ProposalRecallVisitor $revokeVisitor)
    {
        $request = new OrderCancelRequest();
        $request->setVisitor($revokeVisitor);

        /**
         * @var CancelOrderResponse $response
         */
        $response = $this->execute($request);
        return $response;
    }

    /**
     * 撤单接口
     * @param UnderwritingRecallVisitor $recallVisitor
     * @return CancelOrderResponse
     */
    public function underwritingRecall(UnderwritingRecallVisitor $recallVisitor)
    {
        $request = new OrderCancelRequest();
        $request->setVisitor($recallVisitor);

        /**
         * @var CancelOrderResponse $response
         */
        $response = $this->execute($request);
        return $response;
    }

    public function EPolicyDownload(EPolicyDownloadVisitor $EPolicyVisitor)
    {
        $request = new EPolicyDownloadRequest();
        $request->setVisitor($EPolicyVisitor);

        /**
         * @var EPolicyDownloadResponse $response
         */
        $response = $this->execute($request);
        return $response;
    }

    public function policyInfo(PolicyInfoVisitor $policyInfoVisitor)
    {
        $request = new OrderStatusQueryRequest();
        $request->setVisitor($policyInfoVisitor);

        /**
         * @var OrderStatusQueryResponse $response
         */
        $response = $this->execute($request);
        return $response;
    }


    public function UploadFile(UploadFileVisitor $uploadFileVisitor)
    {
        return new UploadFileResponse(200);
    }


    /**
     * 非车产品列表
     * @param NonCarProductListVisitor $nonCarProductListVisitor
     * @return NonCarProductListResponse
     * @version 4.0
     */
    public function nonCarProductList(NonCarProductListVisitor $nonCarProductListVisitor): NonCarProductListResponse
    {
//        $request = new NonCarProductListRequest();
//        $request->setVisitor($nonCarProductListVisitor);
//
//        /*** @var $response NonCarProductListResponse */
//        $response = $this->execute($request);
        $response = new NonCarProductListResponse(200);
        $response->printerInit();
        return $response;
    }

    /**
     * 非车产品列表
     * @param NonCarProductListVisitor $nonCarProductListVisitor
     * @return
     * @version 4.0
     */
    public function nonCarProductDetail(NonCarProductListVisitor $nonCarProductListVisitor)
    {
        $request = new NonCarProductDetailRequest();
        $request->setVisitor($nonCarProductListVisitor);

        /*** @var $response NonCarProductDetailResponse */
        $response = $this->execute($request);

        return $response;
    }

    public function nonCarInquiry(NonCarInquiryVisitor $nonCarInquiryVisitor)
    {
        // TODO: Implement nonCarInquiry() method.
    }

    public function nonCarUnderwriting(NonCarInquiryVisitor $inquiryPrinter)
    {
        // TODO: Implement nonCarUnderwriting() method.
    }
}
